package com.gitee.wsl.test

import kotlin.time.Duration
import kotlinx.coroutines.delay
import kotlinx.coroutines.yield

/**
 * Yields or delays until [expected] equals the result of [actual].
 *
 * Use this to assert asynchronously triggered side effects, such as resource cleanups.
 */
suspend fun <T> awaitEquals(
    expected: T?,
    delay: Duration = Duration.ZERO,
    attempts: Int = 5,
    actual: () -> T?,
) {
    var actualValue = actual()
    if (expected == actualValue) return
    repeat(attempts) {
        if (delay.isPositive()) {
            delay(delay)
        } else {
            yield()
        }
        actualValue = actual()
        if (expected == actualValue) return
    }
    throw AssertionError("$expected != $actualValue")
}
